/**
 * TinyMCE离线富文本编辑器
 */
import React, { useRef, useEffect } from 'react';
import { message } from 'antd';

// 声明TinyMCE全局变量
declare global {
  interface Window {
    tinymce: any;
  }
}

interface TinyMCEEditorProps {
  value?: string;
  onChange?: (content: string) => void;
  placeholder?: string;
  height?: number;
  disabled?: boolean;
}

// 添加全局变量插入方法
declare global {
  interface Window {
    insertVariableToTinyMCE?: (variable: string) => void;
  }
}

const TinyMCEEditor: React.FC<TinyMCEEditorProps> = ({
  value = '',
  onChange,
  placeholder = '请输入内容...',
  height = 400,
  disabled = false
}) => {
  const editorRef = useRef<HTMLTextAreaElement>(null);
  const editorInstanceRef = useRef<any>(null);

  useEffect(() => {
    // 动态加载TinyMCE脚本
    const loadTinyMCE = () => {
      if (window.tinymce) {
        initEditor();
        return;
      }

      const script = document.createElement('script');
      script.src = '/tinymce/tinymce.min.js';
      script.onload = () => {
        initEditor();
      };
      script.onerror = () => {
        message.error('TinyMCE加载失败');
      };
      document.head.appendChild(script);
    };

    const initEditor = () => {
      if (!editorRef.current || editorInstanceRef.current) return;

      window.tinymce.init({
        target: editorRef.current,
        height: height,
        menubar: false,
        license_key: 'gpl', // 声明使用GPL许可
        plugins: [
          'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
          'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
          'insertdatetime', 'media', 'table', 'help', 'wordcount', 'paste'
        ],
        toolbar: 'undo redo | blocks | ' +
          'bold italic underline strikethrough | forecolor backcolor | ' +
          'alignleft aligncenter alignright alignjustify | ' +
          'bullist numlist outdent indent | ' +
          'table | link image | removeformat | code | help',
        content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px; }',
        placeholder: placeholder,
        branding: false,
        resize: false,
        statusbar: false,
        setup: (editor: any) => {
          editorInstanceRef.current = editor;

          // 监听内容变化
          editor.on('change keyup', () => {
            const content = editor.getContent();
            onChange?.(content);
          });

          // 图片上传处理
          editor.on('change', () => {
            const content = editor.getContent();
            onChange?.(content);
          });

          // 设置全局变量插入方法
          window.insertVariableToTinyMCE = (variable: string) => {
            if (editor) {
              editor.insertContent(variable);
              editor.focus();
            }
          };
        },
        images_upload_handler: async (blobInfo: any, progress: any) => {
          return new Promise(async (resolve, reject) => {
            try {
              const formData = new FormData();
              formData.append('file', blobInfo.blob(), blobInfo.filename());

              const token = localStorage.getItem('mailspeed_token') || '';

              const response = await fetch('/api/files/upload/image', {
                method: 'POST',
                body: formData,
                headers: {
                  'Authorization': `Bearer ${token}`
                }
              });

              const result = await response.json();
              
              if (result.success) {
                resolve(`http://localhost:8000${result.data.url}`);
                message.success('图片上传成功');
              } else {
                reject(result.message || '图片上传失败');
                message.error(result.message || '图片上传失败');
              }
            } catch (error: any) {
              reject(error.message || '图片上传失败');
              message.error(error.message || '图片上传失败');
            }
          });
        },
        // 确保文本方向正确
        directionality: 'ltr',
        language: 'zh_CN',
        language_url: '/tinymce/langs/zh_CN.js',
        // 禁用一些可能导问题的功能
        entity_encoding: 'raw',
        verify_html: false,
        cleanup: false,
        convert_urls: false,
        // 确保编辑器正常工作
        base_url: '/tinymce/',
        suffix: '.min',
      });
    };

    loadTinyMCE();

    return () => {
      if (editorInstanceRef.current) {
        window.tinymce.remove(editorInstanceRef.current);
        editorInstanceRef.current = null;
      }
    };
  }, [height, placeholder]);

  // 同步外部值到编辑器
  useEffect(() => {
    if (editorInstanceRef.current && editorInstanceRef.current.getContent() !== value) {
      editorInstanceRef.current.setContent(value || '');
    }
  }, [value]);

  // 处理禁用状态
  useEffect(() => {
    if (editorInstanceRef.current) {
      editorInstanceRef.current.setMode(disabled ? 'readonly' : 'design');
    }
  }, [disabled]);

  return (
    <div className="tinymce-editor">
      <textarea
        ref={editorRef}
        style={{ width: '100%', height: height }}
        defaultValue={value}
      />
      <style>{`
        .tinymce-editor {
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          background: white;
        }
        
        .tinymce-editor :global(.tox-tinymce) {
          border: none !important;
        }
        
        .tinymce-editor :global(.tox-editor-header) {
          border-bottom: 1px solid #d9d9d9 !important;
        }
        
        .tinymce-editor :global(.tox-edit-area) {
          border: none !important;
        }
        
        /* 确保文本方向正确 */
        .tinymce-editor :global(.tox-edit-area iframe) {
          direction: ltr !important;
        }
      `}</style>
    </div>
  );
};

export default TinyMCEEditor;
